import { Feature, Map, View } from "ol";
import { Select } from "ol/interaction.js";
import { Fill, Stroke, Style } from "ol/style.js";
import VectorSource from "ol/source/Vector";
import GeoJSON from "ol/format/GeoJSON.js";
import VectorLayer from "ol/layer/Vector.js";
import CircleStyle from "ol/style/Circle";
import { fromLonLat } from "ol/proj";
import { Point } from "ol/geom";
import { Coordinate } from "ol/coordinate";

export class Base {
  map;
  readonly dom;

  constructor(dom: HTMLElement) {
    this.dom = dom;

    const vectorSource = new VectorSource({
      url: "https://openlayers.org/data/vector/ecoregions.json",
      format: new GeoJSON(),
    });

    const style = new Style({
      fill: new Fill({
        color: "#eeeeee",
      }),
    });
    this.map = new Map({
      target: this.dom,
      layers: [
        new VectorLayer({
          source: vectorSource,
          background: "#1a2b39",
          style: function (feature) {
            const color = feature.get("COLOR_BIO") || "#eeeeee";
            style.getFill()!.setColor(color);
            return style;
          },
        }),
      ],
      view: new View({
        center: [13, 0],
        zoom: 2,
        constrainRotation: 16,
      }),
    });

    const selectedStyle = new Style({
      fill: new Fill({
        color: "rgba(255, 255, 255, 0.6)",
      }),
      stroke: new Stroke({
        color: "rgba(255, 255, 255, 0.7)",
        width: 2,
      }),
    });
    const select = new Select({
      style: function (feature) {
        const color = feature.get("COLOR_BIO") || "#eeeeee";
        selectedStyle.getFill()!.setColor(color);
        return selectedStyle;
      },
    });
    this.map.addInteraction(select);
  }

  creatPoints(points: Coordinate[], layerName: string) {
    // 创建一个Vector数据源
    const vectorSource = new VectorSource();
    // 为点创建样式
    const pointStyle = new Style({
      image: new CircleStyle({
        radius: 5,
        fill: new Fill({ color: "red" }),
        stroke: new Stroke({ color: "white", width: 2 }),
      }),
    });
    // 将点添加到Vector数据源
    points.forEach((point) => {
      const feature = new Feature({
        geometry: new Point(fromLonLat(point)),
      });
      feature.setStyle(pointStyle);
      vectorSource.addFeature(feature);
    });
    // 创建Vector图层并将其添加到地图中
    const vectorLayer = new VectorLayer({
      source: vectorSource,
      style: pointStyle,
    });
    // 设置图层的名称属性
    vectorLayer.set("name", layerName);
    this.map.addLayer(vectorLayer);
  }
  // 查找图层
  findLayerByName(layerName: string) {
    return this.map
      .getLayers()
      .getArray()
      .find((layer) => layer.get("name") === layerName);
  }
  // 删除图层
  removeLayerByName(layerName: string) {
    const layer = this.findLayerByName(layerName);
    if (layer) {
      this.map.removeLayer(layer);
    }
  }
}
